<template>
  <div class="detail-page">
    <van-nav-bar left-text="返回" @click-left="$router.back()" fixed title="面经详细" />
    <header class="header">
      <h1>{{listDetail.stem}}</h1>
      <p>
       创建时间 {{listDetail.createdAt}} | {{listDetail.views}} 浏览量 |
         {{listDetail.likeCount}}  点赞数
      </p>
      <p>
        <img :src="listDetail.avatar" alt />
        <span>{{listDetail.creator}}</span>
      </p>
    </header>
    <main class="body" v-html="listDetail.content"></main>
    <div class="opt">
      <van-icon :class="{ active : listDetail.likeFlag }"    name="like-o"  @click="toggleLike" />
      <van-icon :class="{ active : listDetail.collectFlag }" name="star-o"  @click="toggleCollect"/>
    </div>
  </div>
</template>

<script>
import { detailApi, likeAndCollectApi } from '@/api/article'
export default {
  name: 'detail-page',
  data () {
    return {
      listDetail: { }
    }
  },
  async created () {
    const { data: res } = await detailApi(this.$route.query.id)
    console.log(res)
    this.listDetail = {
      ...res.data
      // collectFlag: '',
      // likeFlag: ''
    }
    // console.log(this.listDetail)
  },
  methods: {
    async toggleLike () {
      this.listDetail.likeFlag = !this.listDetail.likeFlag
      await likeAndCollectApi({
        id: this.listDetail.id,
        optType: 1
      })
      // console.log(this.listDetail)
      if (this.listDetail.likeFlag) {
        this.listDetail.likeCount++
        this.$toast.success('点赞成功')
      } else {
        this.listDetail.likeCount--
        this.$toast.success('取消点赞')
      }
    },
    async toggleCollect () {
      this.listDetail.collectFlag = !this.listDetail.collectFlag
      // console.log(this.listDetail)
      await likeAndCollectApi({
        id: this.listDetail.id,
        optType: 2
      })
      if (this.listDetail.collectFlag) {
        // this.listDetail.likeCount++
        this.$toast.success('收藏成功')
      } else {
        // this.listDetail.likeCount--
        this.$toast.success('取消收藏')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.detail-page {
  margin-top: 44px;
  overflow: hidden;
  padding: 0 15px;
  .header {
    h1 {
      font-size: 24px;
    }
    p {
      color: #999;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .opt {
    position: fixed;
    bottom: 100px;
    right: 0;
    > .van-icon {
      margin-right: 20px;
      background: #fff;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border-radius: 50%;
      box-shadow: 2px 2px 10px #ccc;
      font-size: 18px;
      &.active {
        background: #fec635;
        color: #fff;
      }
    }
  }
}
</style>
